package com.zcf.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.zcf.common.json.Body;
import com.zcf.common.result.PageResult;
import com.zcf.common.result.ResultVo;
import com.zcf.common.utils.DateUtils;
import com.zcf.mapper.*;
import com.zcf.pojo.*;
import com.zcf.service.RidingOrderService;
import com.zcf.utils.DateUtil;
import com.zcf.utils.Hutool;
import com.zcf.vo.in.PageVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zhouzhuang
 * @since 2018-11-28
 */
@Service
public class RidingOrderServiceImpl extends ServiceImpl<RidingOrderMapper, RidingOrder> implements RidingOrderService {
    @Autowired
    private RidingOrderMapper ridingOrderMapper;
    @Autowired
    private RidingMapper ridingMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderinfoMapper orderinfomapper;
    @Autowired
    private LogMapper logMapper;
    @Autowired
    private FreightMapper freightMapper;

    public ResultVo myOrderList(PageVo pv, String userId, int type) {
        RidingOrder ridingOrder = new RidingOrder();
        EntityWrapper<RidingOrder> ew = new EntityWrapper<RidingOrder>();
        ew.eq("riding_id", userId);
//		ew.eq("type", type);
//		List<RidingOrder> list = ridingOrderMapper.selectList(ew);
        List<RidingOrder> list = ridingOrder.selectList(ew);
        ResultVo rv = new ResultVo();
        System.err.println(list.size());
        if (list.size() > 0) {
            if (pv.getPage() != null && pv.getPageSize() != null) {
                PageHelper.startPage(pv.getPage(), pv.getPageSize());
            }
            PageResult pr = PageResult.result(ridingOrder.selectList(ew));
            rv.setList(pr.getRows());
            rv.setTotal(pr.getTotal());
        }
        return rv;
    }

    public Body ridingGet(String id) {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = sdf.format(date);
        RidingOrder order = new RidingOrder();
        order.setId(id);
        RidingOrder one = ridingOrderMapper.selectById(id);
        if (one != null && !"".equals(one)) {
            one.setGetTime(time);
            one.setType(1);// 取货
            ridingOrderMapper.updateById(one);
            return Body.newInstance(one);
        }
        return Body.newInstance(501, "订单不存在");
    }

    public Body endOrder(String id) {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = sdf.format(date);
        RidingOrder order = new RidingOrder();
        order.setId(id);
        RidingOrder one = ridingOrderMapper.selectById(id);
        if (one != null && !"".equals(one)) {
            String orderId = one.getOrderId();
            one.setEndTime(time);
            one.setType(2);// 确认送达
            Integer sum = ridingOrderMapper.updateById(one);
            if (sum > 0) {
                Orderinfo ord = new Orderinfo();
                ord.setOrderInfoId(orderId);
                Orderinfo orde = ord.selectById();
                if (orde != null) {
                    orde.setStatus(2);// 待评价
                    orde.setDinStatus(2);// 配送完成
                    orde.setCompletionTime(Hutool.parseDateToString());
                    orde.updateById();

                    Orderinfo orders = orderinfomapper.selectById(orde.getOrderInfoId());
                    Double totalMoenys = orders.getTotalMoney();

                    String times = DateUtil.dateDiff(orders.getPredictTime(), orders.getCompletionTime(),
                            "yyyy-MM-dd HH:mm:ss", "m");
                    if (Integer.parseInt(times) > 0) {
                        Log log = new Log();
                        log.setLogId(Hutool.getId());
                        log.setAddtime(Hutool.parseDateToStringMM());
                        log.setLogDesc("骑手评价");
                        log.setLogName("迟到送达");
                        log.setUserId(one.getRidingId());
                        log.insert();
                    }

                    User userq = new User();
                    userq.setId(one.getRidingId());
                    userq = userq.selectById();

                    // 骑手佣金
                    Riding riding = new Riding();
                    EntityWrapper<Riding> pwe = new EntityWrapper<>();
                    pwe.eq("user_id", userq.getId());
                    riding = riding.selectOne(pwe);
                    if (riding != null) {
                        Freight freight = new Freight();
                        freight = freightMapper.selectf();
                        User user = new User();
                        user.setId(riding.getUserId());
                        user = user.selectById();
                        totalMoenys = totalMoenys - freight.getMoneys();
                        user.setMoney(user.getMoney() + freight.getMoneys());
                        Boolean flag = user.updateById();
                        if (flag) {
                            Log log = new Log();
                            log.setAddtime(DateUtils.formatTimeNow());
                            log.setLogDesc("骑手收入");
                            log.setLogType(1);
                            log.setLogName("骑手:" + user.getName() + "收入" + freight.getMoneys() + "元");
                            log.setLogId(Hutool.getId());
                            log.setUserId(user.getId());
                            log.setOrderId(orders.getOrderInfoId());
                            log.setMoneys(freight.getMoneys() + "");
                            logMapper.insert(log);
                        }
                    }
                    // 商家和代理到账金额
                    Subordinate subordinate = new Subordinate();
                    EntityWrapper<Subordinate> ews = new EntityWrapper<>();
                    ews.eq("din_id", orders.getDinId());
                    subordinate = subordinate.selectOne(ews);
                    Freight freight = new Freight();

                    if (subordinate != null) {
                        Dining dining = new Dining();
                        dining.setId(subordinate.getDinId());
                        dining = dining.selectById();
                        if (dining != null) {
                            User users = new User();
                            users.setId(dining.getUserId());
                            users = users.selectById();
                            if (users != null) {
                                // 获取抽成
                                Double money = (double) subordinate.getProportion() / 100;
                                // 总共抽成
                                Double sum1 = totalMoenys * money;
                                // 商家金额
                                totalMoenys = totalMoenys - sum1;
                                totalMoenys = Double.valueOf(totalMoenys + Double.valueOf(orders.getCouponMoney())) ;
                                users.setMoney(users.getMoney() + totalMoenys);
                                users.updateById();

                                Log log = new Log();
                                log.setLogId(Hutool.getId());
                                log.setAddtime(DateUtils.formatTimeNow());
                                log.setLogDesc("商家收入");
                                log.setLogType(1);
                                log.setLogName("商家:" + dining.getDiningName() + "收入" + totalMoenys + "元");
                                log.setLogId(Hutool.getId());
                                log.setUserId(users.getId());
                                log.setOrderId(orders.getOrderInfoId());
                                log.setMoneys(totalMoenys + "");
                                logMapper.insert(log);

                                Percentage percentage = new Percentage();
                                EntityWrapper<Percentage> ew = new EntityWrapper<>();
                                ew.eq("user_id", subordinate.getUserId());
                                percentage = percentage.selectOne(ew);
                                if (percentage != null) {
                                    Double dailiMoney = (double) percentage.getProportion() / 100;
                                    // 平台抽成
                                    Double num = sum1 * dailiMoney;
                                    // 代理抽成
                                    sum1 = sum1 - num;
                                    User user = new User();
                                    user.setId(percentage.getUserId());
                                    user = user.selectById();
                                    if (user != null) {
                                        user.setMoney(user.getMoney() + sum1);
                                        user.updateById();

                                        Log log1 = new Log();
                                        log1.setLogId(Hutool.getId());
                                        log1.setAddtime(DateUtils.formatTimeNow());
                                        log1.setLogDesc("代理收入");
                                        log1.setLogType(1);
                                        log1.setLogName("代理:" + user.getName() + "收入,商家：" + dining.getDiningName() + ":"
                                                + sum1 + "元");
                                        log1.setLogId(Hutool.getId());
                                        log1.setUserId(users.getId());
                                        log1.setOrderId(orders.getOrderInfoId());
                                        log1.setMoneys(sum1 + "");
                                        Integer flag = logMapper.insert(log1);

                                        if (flag > 0) {
                                            return Body.newInstance(one);
                                        }
                                        return Body.BODY_200;
                                    }
                                    return Body.BODY_200;
                                }
                                return Body.BODY_200;
                            }
                            return Body.BODY_200;
                        }
                        return Body.BODY_200;
                    } else {
                        Orderinfo orderinfo = new Orderinfo();
                        EntityWrapper<Orderinfo> ew = new EntityWrapper<>();
                        ew.eq("order_info_id", orderId);
                        orderinfo = orderinfo.selectOne(ew);

                        Dining dining = new Dining();
                        dining.setId(orderinfo.getDinId());
                        dining = dining.selectById();
                        if (dining != null) {
                            User users = new User();
                            users.setId(dining.getUserId());
                            users = users.selectById();
                            // 商家金额
                            users.setMoney(users.getMoney() + totalMoenys);
                            users.updateById();

                            Log log = new Log();
                            log.setLogId(Hutool.getId());
                            log.setAddtime(DateUtils.formatTimeNow());
                            log.setLogDesc("商家收入");
                            log.setLogType(1);
                            log.setLogName(dining.getDiningName() + "收入" + totalMoenys + "元");
                            log.setLogId(Hutool.getId());
                            log.setUserId(users.getId());
                            log.setOrderId(orders.getOrderInfoId());
                            log.setMoneys(totalMoenys + "");
                            Integer falg = logMapper.insert(log);
                            if (falg > 0) {
                                return Body.newInstance(one);
                            }
                        }
                    }
                    return Body.newInstance(one);
                }
                return Body.newInstance(501, "客户未下单");
            }
            return Body.newInstance(-1, "失败");
        }
        return Body.newInstance(501, "没有此订单");
    }

}
